package org.opensuse.bs.ui.actions;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Vector;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.opensuse.bs.ui.OSC;


public class CommitAction implements IObjectActionDelegate {
	private Object[] objs;
	
	private class LogDialog extends Dialog {
		private Text content;

		protected LogDialog(Shell parentShell) {
			super(parentShell);
		}
		
		protected void configureShell(Shell newShell) {
			super.configureShell(newShell);
			newShell.setText("log file");
		}
		
		protected Control createDialogArea(Composite parent) {
			Composite client = new Composite(parent, SWT.NONE);
			GridLayout layout = new GridLayout();
			client.setLayout(layout);
			content = new Text(client, SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL);
			GridData gd = new GridData();
			content.setLayoutData(gd);
			gd.grabExcessHorizontalSpace = true;
			gd.widthHint = 300;
			gd.heightHint = 200;
			return client;
		}
		
		protected  void 	okPressed() {
			try {
				final File logFile = File.createTempFile("commit", "osc");
				FileWriter out = new FileWriter(logFile);
				BufferedWriter output = new BufferedWriter(out);
				output.write(content.getText().trim());
				output.close();
				Job job = new Job("Committing...") {
					public IStatus run(IProgressMonitor monitor) {
						monitor.beginTask("Committing...", objs.length);
						try {
							for(int i=0;i<objs.length;i++) {
								if(monitor.isCanceled())
									return Status.CANCEL_STATUS;
							    IResource r = (IResource) objs[i];
							    final String name = r.getName();
							    monitor.subTask("Committing "+name);
							    Vector<String> result = new Vector<String>();
							    if(objs[i] instanceof IFile) {
							    	File dir = new File(r.getParent().getLocation().toOSString());
							    	if(dir.exists() && dir.isDirectory()) {
								    	String cmd = "ci "+name+" -F "+logFile.getAbsolutePath();
								    	OSC.run(cmd, null, dir);
							    	}
							    }else if(objs[i] instanceof IFolder) {
							    	File dir = new File(r.getLocation().toOSString());
							    	if(dir.exists() && dir.isDirectory()) {
								    	String cmd = "ci -F "+logFile.getAbsolutePath();
								    	OSC.run(cmd, null, dir);
							    	}
							    }else {
							    	File dir = new File(r.getLocation().toOSString());
							    	if(dir.exists() && dir.isDirectory()) {
							    		String[] files = dir.list();
								    	for(int j=0;j<files.length;j++) {
								    		if(files[j].startsWith("."))continue;
								    		File file = new File(dir.getAbsolutePath()+"/"+files[j]);
								    		String cmd = "ci -F "+logFile.getAbsolutePath();
								    		result = OSC.run(cmd, null, file);
								    		if(result.isEmpty())continue;
								    	}
							    	}
							    }
							    logFile.delete();
							    r.refreshLocal(IResource.DEPTH_INFINITE, monitor);
							    monitor.worked(1);
							}
						}catch(Exception e) {
							e.printStackTrace();
						}finally {
							monitor.done();
						}
						return Status.OK_STATUS;
					}
				};
				job.schedule();
			}catch(Exception e) {
				e.printStackTrace();
			}
			close();
		}
		
	}
	
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		objs = new Object[0];
	}
	
	public void run(IAction action) {
		Dialog dialog = new LogDialog(null);
		dialog.open();
	}
	
	public void selectionChanged(IAction action, ISelection selection) {
		if(selection instanceof ITreeSelection) {
			ITreeSelection selected = (ITreeSelection) selection;
			TreePath[] paths = selected.getPaths();
			if(paths.length != 0) {
				objs = new Object[paths.length];
				for(int i=0;i<paths.length;i++) {
					objs[i] = paths[i].getLastSegment();
				}
			}
		}
	}
}
